var express = require("express");
var router = express.Router();
const addressModel = require("../../models/addressesModel");
const mongoose = require("mongoose");

let provinceSchema = new mongoose.Schema({
  code: String,
  name: String,
});
let citySchema = new mongoose.Schema({
  code: String,
  name: String,
  provinceCode: String,
});
let areaSchema = new mongoose.Schema({
  code: String,
  name: String,
  cityCode: String,
  provinceCode: String,
});

let provinceModel = mongoose.model("provinces", provinceSchema);
let cityModel = mongoose.model("cities", citySchema);
let areaModel = mongoose.model("areas", areaSchema);

// 获取收货地址列表
router.get("/", (req, res) => {
  let { userId } = req.query;
  addressModel
    .find({ userId })
    .select({ __v: 0 })
    .sort({ isDefault: -1 })
    .then((data) => {
      if (data.length === 0) {
        return res.json({
          code: 200,
          data,
          msg: "数据为空",
        });
      }
      return res.json({
        code: 200,
        data,
        msg: "获取地址成功~",
      });
    })
    .catch((err) => {
      return res.json({
        code: "1001",
        msg: "数据库读取失败~~~",
        data: null,
      });
    });
});

// 新增收货地址
router.post("/", async (req, res) => {
  let { province, city, area, userId, receiver, addr, mobile, isDefault } =
    req.body;
  let p = await provinceModel.findOne({ code: province });
  let c = await cityModel.findOne({ code: city });
  let a = await areaModel.findOne({ code: area });
  addressModel
    .create({
      userId,
      receiver,
      province: p.name,
      city: c.name,
      area: a.name,
      addr,
      mobile,
      isDefault,
    })
    .then((data) => {
      if (!data) {
        return res.json({
          code: -1,
          msg: "新增失败",
          data: null,
        });
      }
      return res.json({
        code: 200,
        msg: "新增收货地址成功",
        data: data,
      });
    })
    .catch((err) => {
      return res.json({
        code: "1001",
        msg: "数据库读取失败~~~",
        data: null,
      });
    });
});

// 修改收货地址
router.put("/", async (req, res) => {
  let { _id, province, city, area, receiver, addr, mobile, isDefault } = req.body;
  if (isNaN(Number(province)) && isNaN(Number(city) && isNaN(Number(area)))) {
    addressModel
      .updateOne({ _id }, { ...req.body })
      .then((data) => {
        if (!data.acknowledged) {
          return res.json({
            code: -1,
            msg: "修改失败",
            data: null,
          });
        }
        return res.json({
          code: 200,
          msg: "地址修改成功~",
          data: null,
        });
      })
      .catch((err) => {
        return res.json({
          code: "1001",
          msg: "数据库读取失败~~~",
          data: null,
        });
      });
  } else {
    console.log(2);
    let p = await provinceModel.findOne({ code: province });
    let c = await cityModel.findOne({ code: city });
    let a = await areaModel.findOne({ code: area });
    addressModel
      .updateOne(
        { _id },
        {
          receiver,
          province: p.name,
          city: c.name,
          area: a.name,
          addr,
          mobile,
          isDefault,
        }
      )
      .then((data) => {
        if (!data.acknowledged) {
          return res.json({
            code: -1,
            msg: "修改失败",
            data: null,
          });
        }
        return res.json({
          code: 200,
          msg: "地址修改成功~",
          data: null,
        });
      })
      .catch((err) => {
        return res.json({
          code: "1001",
          msg: "数据库读取失败~~~",
          data: null,
        });
      });
  }
});

// 删除收货地址
router.delete("/:_id", async (req, res) => {
  let { _id } = req.params;
  let addr = await addressModel.findById(_id);
  if (addr.isDefault) {
    return res.json({
      code: -1,
      data: null,
      msg: "不能删除默认地址！",
    });
  }
  addressModel
    .deleteOne({ _id })
    .then((result) => {
      if (result.deletedCount !== 0) {
        return res.json({
          code: 200,
          msg: "删除成功",
          data: null,
        });
      }
      return res.json({
        code: -1,
        msg: "删除失败",
        data: null,
      });
    })
    .catch((err) => {
      return res.json({
        code: "1001",
        msg: "数据库读取失败~",
        data: null,
      });
    });
});

// 设置默认地址
router.post("/setDefault", async (req, res) => {
  try {
    let { userId, _id } = req.body;
    await addressModel.updateMany({ userId }, { isDefault: false });
    await addressModel.updateOne({ _id }, { isDefault: true });
    return res.json({
      code: 200,
      data: null,
      msg: "设置默认地址成功",
    });
  } catch (err) {
    res.status(400).json({ msg: "设置失败！" });
  }
});

// 获取省份数据
router.get("/province", (req, res) => {
  provinceModel
    .find()
    .then((data) => {
      if (data.length === 0) {
        return res.json({
          code: 200,
          data,
          msg: "数据为空",
        });
      }
      return res.json({
        code: 200,
        data,
        msg: "获取数据成功~",
      });
    })
    .catch((err) => {
      return res.json({
        code: "1001",
        msg: "数据库读取失败~~~",
        data: null,
      });
    });
});

// 获取市数据
router.get("/city", async (req, res) => {
  let { provinceCode } = req.query;
  cityModel
    .find({ provinceCode })
    .then((data) => {
      if (data.length === 0) {
        return res.json({
          code: 200,
          data,
          msg: "数据为空",
        });
      }
      return res.json({
        code: 200,
        data,
        msg: "获取数据成功~",
      });
    })
    .catch((err) => {
      return res.json({
        code: "1001",
        msg: "数据库读取失败~~~",
        data: null,
      });
    });
});

// 获取区数据
router.get("/area", async (req, res) => {
  let { cityCode } = req.query;
  areaModel
    .find({ cityCode })
    .then((data) => {
      if (data.length === 0) {
        return res.json({
          code: 200,
          data,
          msg: "数据为空",
        });
      }
      return res.json({
        code: 200,
        data,
        msg: "获取数据成功~",
      });
    })
    .catch((err) => {
      return res.json({
        code: "1001",
        msg: "数据库读取失败~~~",
        data: null,
      });
    });
});

module.exports = router;
